package client

import (
	"context"
	"errors"
	"fmt"
	"github.com/zhongshaofa/swan-jobs/internal/models"
	"github.com/zhongshaofa/swan-jobs/internal/rpc/proto/client"
	"github.com/zhongshaofa/swan-jobs/internal/services"
	"github.com/zhongshaofa/swan-jobs/internal/utils/system"
	"google.golang.org/grpc"
	"log"
	"net"
)

type Server struct {
	client.UnimplementedServiceServer
}

// RunTask 执行任务
func (s *Server) RunTask(ctx context.Context, request *client.TaskRequest) (*client.TaskResponse, error) {

	parameter := services.ClientParameter{
		Directory:  request.Directory,
		Command:    request.Command,
		Timeout:    int(request.Timeout),
		TaskId:     int(request.TaskId),
		ScheduleId: int(request.ScheduleId),
		Mode:       int(request.Mode),
		ClientId:   int(request.ClientId),
	}

	message := fmt.Sprintf("command:%s, taskId:%v , parameter:%v", request.Command, request.TaskId, parameter)

	go func(parameter services.ClientParameter) {
		services.ParameterChan <- parameter
	}(parameter)

	fmt.Printf("parameter：%+v\n", parameter)

	return &client.TaskResponse{Message: message, Pid: 0, ErrorCode: 0}, nil
}

// Heartbeat 检查服务心跳
func (s *Server) Heartbeat(ctx context.Context, request *client.HeartbeatRequest) (*client.HeartbeatResponse, error) {
	response := client.HeartbeatResponse{
		ClientId:      request.ClientId,
		CpuPercent:    int32(system.GetIdleCpuPercent()),
		MemoryPercent: int32(system.GetIdleMemoryPercent()),
	}
	return &response, nil
}

// ExistTask 判断服务中是否存在任务
func (s *Server) ExistTask(ctx context.Context, request *client.CommonTaskRequest) (*client.ExistTaskResponse, error) {
	if int(request.Mode) == models.ModeSupervisor {
		exist, _ := services.GetClientSupervisorTaskManageInstance().Exist(int(request.TaskId))
		return &client.ExistTaskResponse{
			Exist:    exist,
			ClientId: request.ClientId,
		}, nil
	} else {
		return nil, errors.New("暂未实现对该类型任务的监听功能")
	}
}

// ReloadTask 重新加载任务
func (s *Server) ReloadTask(ctx context.Context, request *client.TaskRequest) (*client.TaskResponse, error) {
	if int(request.Mode) == models.ModeSupervisor {
		err := services.GetClientSupervisorTaskManageInstance().Reload(&services.ClientParameter{
			Directory:  request.Directory,
			Command:    request.Command,
			Timeout:    int(request.Timeout),
			TaskId:     int(request.TaskId),
			ScheduleId: int(request.ScheduleId),
			Mode:       int(request.Mode),
			ClientId:   int(request.ClientId),
		})
		if err != nil {
			return nil, err
		}
		return &client.TaskResponse{Message: "ReloadTask success", Pid: 0, ErrorCode: 0}, nil
	} else {
		return nil, errors.New("暂未实现对该类型任务的重新加载功能")
	}
}

// StopTask 停止任务
func (s *Server) StopTask(ctx context.Context, request *client.CommonTaskRequest) (*client.TaskResponse, error) {
	if int(request.Mode) == models.ModeSupervisor {
		services.GetClientSupervisorTaskManageInstance().Stop(int(request.TaskId))
		return &client.TaskResponse{Message: "StopTask success", Pid: 0, ErrorCode: 0}, nil
	} else {
		return nil, errors.New("暂未实现对该类型任务的重新加载功能")
	}
}

// StopAllTask 停止所有任务
func (s *Server) StopAllTask(ctx context.Context, request *client.CommonTaskRequest) (*client.TaskResponse, error) {
	if int(request.Mode) == models.ModeSupervisor {
		services.GetClientSupervisorTaskManageInstance().AllStop()
		return &client.TaskResponse{Message: "StopTask success", Pid: 0, ErrorCode: 0}, nil
	} else {
		return nil, errors.New("暂未实现对该类型任务的重新加载功能")
	}
}

func Start(address string) {
	lis, err := net.Listen("tcp", address)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	client.RegisterServiceServer(s, &Server{})
	log.Printf("server listening at %v", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
